package com.suray.basic.wcs.plc.pojo.oper.single;

import com.suray.basic.wcs.plc.core.PlcOffset;
import com.suray.basic.wcs.plc.enums.Location;
import com.suray.basic.wcs.plc.enums.PlcDeviceType;
import com.suray.basic.wcs.utils.Coord;
import com.suray.basic.wcs.utils.ParamConfig;
import com.suray.basic.wcs.utils.WcsFuncUtil;

/**
 * 扫码读取
 */
public class ScanOper extends ShapeConveyorOper {

    private static final PlcOffset SCAN_CAN_READ = new PlcOffset(0, null);
    private final int maxBarCode = 15;

    private final static int highBit = 8;
    private final static int lowBit = 0;
    private final static int startNum = 27;

    public ScanOper(PlcDeviceType plcDeviceType, int startNo, String deviceName, int deviceNo, Coord coord,
                    Location location, Coord lockLocation, long deviceId, Integer gridzMax, Integer gridzRelative,
                    int plcId) {
        super(plcDeviceType, startNo, deviceName, deviceNo, coord, location, lockLocation, deviceId, gridzMax,
                gridzRelative, plcId);
    }

    public boolean isScanCanRead() {
        return readPlc(SCAN_CAN_READ) == 1;
    }

    public boolean isScanError() {
        return readPlc(SCAN_CAN_READ) == 2;
    }

    /**
     * 获取扫码结果
     * 起始字节为扫码值有效值，后面15个字节用于码值解析
     * 码值解析按byte读取，0x2为起始标志，0x3为结束标志，中间为实际码值
     *
     * @return 条码值
     */
    public String getCodeData() {
        StringBuilder sb = new StringBuilder();
        int code_value;
        boolean allow_analyze_code = false;
//        PlcOffset plcOffset = new PlcOffset(getStartNo(), null);
        for (int i = 1; i <= maxBarCode; i++) {
            for (int j = 0; j < 2; j++) {
                try {
                    code_value = getBarCodeByBit(i, ((j % 2) == 0) ? highBit : lowBit);
//                plcOffset.setAddressOffset(getStartNo() + i);
//                code_value = readPlc(plcOffset);

                    if (!allow_analyze_code) {
                        if (code_value == ParamConfig.scanStartFlag) {
                            allow_analyze_code = true;
                        }
                    } else {
                        if (code_value == ParamConfig.scanEndFlag) {
                            break;
                        }
                        sb.append((char) code_value);
                    }
                } catch (Exception e) {
                    WcsFuncUtil.exceptionLog(e, this.getClass());
                    return "扫码解析异常";
                }
            }
        }
        return sb.toString();
    }
}
